package com.dong.auth.security.authentication;

import com.dong.auth.security.exception.AccountStatusException;
import com.dong.auth.security.exception.AuthenticationException;
import com.dong.auth.security.exception.AuthenticationServiceException;
import com.dong.auth.security.userdetails.SecurityUser;

/**
 * 抽象认证授权类
 *
 * @author zhaodongchao
 * @version V1.0
 * @date 2021/10/25 22:20
 */
public abstract class AbstractAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取登录名
        String accessCode = authentication.getAccessCode();
        SecurityUser securityUser = retrieveUser(accessCode);
        //认证成功之后校验账户的状态
        if (securityUser.isLocked()) {
            throw new AccountStatusException(String.format("当前登录账户[%s]已经被锁定", accessCode));
        }
        if (securityUser.isCredentialsExpired()) {
            throw new AccountStatusException(String.format("当前登录账户[%s]密码已过期", accessCode));
        }
        //检查登录账户的密码
        additionalAuthenticationChecks(securityUser, authentication);

        //登录成功
        authentication.setAuthenticated(true);
        authentication.setAuthorities(securityUser.getAuthorities());
        authentication.setUserDetail(securityUser);
        return authentication;
    }

    protected abstract SecurityUser retrieveUser(String username) throws AuthenticationException;

    protected abstract void additionalAuthenticationChecks(SecurityUser userDetails, Authentication authentication) throws AuthenticationException;
}
